#!/usr/bin/env python3
"""
后端API密钥提取工具
从Java后端日志中提取API密钥并保存到配置文件
"""

import os
import re
import json
from typing import Optional


def extract_api_key_from_logs() -> Optional[str]:
    """从后端日志中提取API密钥"""
    log_files = ["logs/system.log", "target/backend.log", "system.log"]

    # API密钥的正则表达式模式 - 更精确的匹配
    api_key_patterns = [
        r"管理员API密[钥鍵][:：]\s*([A-Za-z0-9+/=]{40,})",
        r"API密[钥鍵][:：]\s*([A-Za-z0-9+/=]{40,})",
    ]

    all_keys_with_position = []

    for log_file in log_files:
        try:
            if os.path.exists(log_file):
                print(f"检查日志文件: {log_file}")

                # 尝试不同编码
                encodings = ["utf-8", "gbk", "cp936", "latin1"]
                lines = None

                for encoding in encodings:
                    try:
                        with open(
                            log_file, "r", encoding=encoding, errors="ignore"
                        ) as f:
                            lines = f.readlines()
                        break
                    except:
                        continue

                if lines:
                    for line_num, line in enumerate(lines):
                        for pattern in api_key_patterns:
                            matches = re.findall(pattern, line)
                            for match in matches:
                                key = match.strip()
                                if len(key) >= 40:
                                    # 存储 (文件位置，行号，密钥) - 行号越大越新
                                    all_keys_with_position.append(
                                        (log_file, line_num, key)
                                    )
                                    print(
                                        f"找到API密钥: {key} (文件: {log_file}, 行: {line_num+1})"
                                    )

        except Exception as e:
            print(f"读取日志文件 {log_file} 失败: {e}")

    # 选择最新的密钥 (行号最大的)
    if all_keys_with_position:
        # 按行号排序，取最后一个（最新的）
        latest = max(all_keys_with_position, key=lambda x: x[1])
        latest_key = latest[2]
        print(f"选择最新的API密钥: {latest_key}")
        return latest_key

    return None
    return None


def save_api_key_config(api_key: str):
    """保存API密钥到配置文件"""
    config = {"api_key": api_key, "backend_host": "localhost", "backend_port": 8889}

    config_file = "tui_config.json"
    try:
        with open(config_file, "w", encoding="utf-8") as f:
            json.dump(config, f, indent=2, ensure_ascii=False)
        print(f"API密钥已保存到: {config_file}")
    except Exception as e:
        print(f"保存配置文件失败: {e}")


def main():
    print("分布式文件同步系统 - API密钥提取工具")
    print("=" * 50)

    api_key = extract_api_key_from_logs()
    if api_key:
        save_api_key_config(api_key)
        print("\n✅ API密钥提取成功!")
        print(f"API密钥: {api_key}")
        print("\n现在可以运行 simple_tui.py 连接后端服务")
    else:
        print("\n❌ 未找到API密钥")
        print("请确保:")
        print("1. Java后端服务已启动")
        print("2. 日志文件存在且包含API密钥信息")


if __name__ == "__main__":
    main()
